// pages/reservation/reservation.js
let app = getApp()
const mobileReg = /^(13|15|17|18|14|19|16)[0-9]{9}$/

import { requestApi } from '../../api'
import { formatImage } from '../../utils/formatImage'
import { formatTimeHMS, formatPrice } from '../../utils/util'
import { colorSelect, specSelect } from '../../templates/goodsSku/goodsSku'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    swiperData: [],
    reservationGoods: {},
    progressList: [],
    activeImage: [],
    goodsData: {},
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    _phoneNumber: '',
    phoneAllNumber: '',
    _flag: false,
    _errortext: '',
    skuHidden: true,
    skuList: '',
    skuColorId: '',
    skuSpecId: '',
    skuSpecVal: '',
    skuPrice: '',
    skuImage: '',
    skuId: '',
    disableFlag: false,
    git: '',
    // priceFlog: true,  //价格标识
    reservationStatus: true,
    reservationPrice: '',
    reservationGoodsInfo: '',
    showAddress: true,
    addressData: '',
    activityId: '',
    channel: '',
    showRequest: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let scene = ''
    let paramArr = []
    let channel = ''
    let activity_id = ''

    if (options.scene && options.scene.length) {
      scene = decodeURIComponent(options.scene)
      paramArr = scene.split(',')

      if (paramArr[1] == 'sl') {
        app.shortUrlToLong(paramArr[0], (res) => {
          activity_id = res.activity_id
          channel = res.channel       
        })
      } else {
        activity_id = paramArr[0]
        channel = paramArr[1]
      }
    } else {
      channel = options.channel || 'wx_xcx'
      activity_id = options.activity_id
    }

    this.setData({
      activityId: activity_id,
      channel: channel
    })

    if (!app.toActivityLogin()) {
      return false
    }

    wx.setStorage({
      key: 'selectIndex',
      data: -1,
    })
  },

  onShow: function(options) {

    this.getReservationData(this.data.activityId, this.data.channel)
  },

  getReservationData: function (activity_id, channel) {
    app.request({
      url: requestApi.reservationGoodsUrl,
      data: {
        reservation_id: activity_id,
        channel: channel
      }
    }, (data) => {
      let swiperData, reservationGoodsInfo, progressList, activeImage, goodsData, reservation_out_time, skuPrice, reservationPrice

      if (data.original.data.item_list && data.original.data.item_list.length) {
        data.original.data.item_list.forEach((item, index) => {
          switch (index) {
            case 0:
              swiperData = item.data.image_list
              swiperData.forEach((imageItem) => {
                imageItem.new_path = formatImage.cdnImage(imageItem.path, formatImage.THUMBNAIL_L)
              })
            break;
            case 1:
              reservationGoodsInfo = item.data
              if (isNaN(parseInt(reservationGoodsInfo.activity_describe))) {
                reservationPrice = reservationGoodsInfo.activity_describe
              } else {
                reservationPrice = reservationGoodsInfo.activity_describe
              }
            break;
            case 2:
              progressList = item.data.progress_list
            break;
            case 3:
              activeImage = item.data.image_list

              activeImage.forEach((imageItem) => {
                imageItem.new_path = formatImage.cdnImage(imageItem.path, formatImage.THUMBNAIL_L)
              })
            break;
          }
        })
      }

      if (data.original.data.goods_info) {
        goodsData = data.original.data.goods_info
      }

      if (goodsData.product_cover_image && goodsData.product_cover_image.path) {
        goodsData.product_cover_image.new_path = formatImage.cdnImage(goodsData.product_cover_image.path, formatImage.THUMBNAIL_M)
      }

      goodsData.new_goods_price = goodsData.goods_price ? formatPrice(goodsData.goods_price / 100) : ''

      if (goodsData.button_text == '等待抽取' || goodsData.button_text == '立即预约') {
        let reservation_out_time, seconds = 0, timer
        
        timer = setInterval(() => {
          seconds++
          let time_out = goodsData.reservation_out_time  - seconds
          reservation_out_time = formatTimeHMS(time_out)

          if (reservation_out_time == '00:00:00') {
            this.setData({
              reservation_out_time: '00:00:00',
            })
            clearInterval(timer)
          } else {
            this.setData({
              reservation_out_time: reservation_out_time,
            })
          }
        }, 1000)
      }

      if (goodsData.goods_sku) {
        goodsData.goods_sku.forEach((item) => {
          if (item.image_list[0].path) {
            item.image_list[0].new_path = formatImage.cdnImage(item.image_list[0].path, formatImage.THUMBNAIL_S)
          }

          item.new_goods_price = item.goods_price ? (item.goods_price / 100) : ''

          item.goods_single_price_calculate = item.original_price ? (item.original_price / 100) : 0

          item.goods_price_calculate = item.goods_price ? (item.goods_price / 100) : 0
        })
      }

      this.setData({
        swiperData: swiperData,
        reservationGoodsInfo: reservationGoodsInfo,
        reservationPrice: reservationPrice,
        progressList: progressList,
        activeImage: activeImage,
        goodsData: goodsData,
        skuImage: goodsData.product_cover_image.new_path,
        skuPrice: goodsData.new_goods_price,
        _phoneNumber: goodsData.mobile_phone ? goodsData.mobile_phone.replace(/(\d{3})\d+(\d{4})/, '$1*****$2') : '',
        phoneAllNumber: goodsData.mobile_phone,
        gid: goodsData.gid,
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.dialog = this.selectComponent("#dialog");
    this.doneDialog = this.selectComponent('#doneDialog')
  },

  remindTap: function (e) {
    let reservationStatus = this.data.goodsData.already_reservation
    let is_reservation = this.data.goodsData.is_reservation
    let is_send_sms = this.data.goodsData.is_send_sms

    if (is_send_sms == 2) {
      return false
    }
    if (is_reservation == 1) {
      if (reservationStatus == 1) {
        this.dialog.showDialog()
      } else if (reservationStatus == 2) {
        this.setData({
          skuHidden: false,
        })
      }
    } else {
      wx.showModal({
        title: '提示',
        content: '该商品不可预约',
        showCancel: false
      })
    }
  },

  _inputNumber(eventDetail) {
    let phoneNumber = eventDetail.detail.value

    this.setData({
      phoneAllNumber: phoneNumber
    })
  },

  _cancelEvent() {
    this.dialog.hideDialog();
    this.setData({
    })
  },

  //确认事件，注：此方法为外界传入组件的回调，组件内部已做处理.
  _confirmEvent(e) {
    let phoneNumber = this.data.phoneAllNumber

    if (phoneNumber == '') {
      this.setData({
        _flag: true,
        _errorText: '输入不能为空'
      })
    } else if (!mobileReg.test(phoneNumber)) {
      this.setData({
        _flag: true,
        _errorText: '请输入正确的手机号'
      })
    } else {
      setTimeout(() => {
        this.dialog.hideDialog();
        
        app.request({
          url: requestApi.phoneInfoUrl,
          method: "POST",
          data: {
            reservation_id: this.data.goodsData.activity_id,
            mobile_phone: phoneNumber,
            gid: this.data.goodsData.gid
          }
        }, (data) => {
          if (data.original.status == 'success') {
            wx.showToast({
              title: '设置成功',
            })
          }
          this.setData({
            disableFlag: true
          })
        })
      },300)
      
      this.setData({
        _flag: false,
        _phoneNumber: '',
        _errorText: ''
      })
    }
  },

  toggleSku() {
    let skuFlag = this.data.skuHidden
    let skuPrice = this.data.goodsData.new_goods_price
    let goodsData = this.data.goodsData

    for (let i = 0, len = goodsData.goods_color_list.length; i < len; i++) {
      goodsData.goods_color_list[i].noStock = false
    }

    for (let i = 0, len = goodsData.goods_size_list.length; i < len; i++) {
      goodsData.goods_size_list[i].noStock = false
    }

    this.setData({
      goodsData: goodsData,
      skuHidden: !skuFlag,
      skuPrice: skuPrice,
      colorStyle: 0,
      specStyle: 0,
      skuColorId: '',
      skuSpecId: '',
      addressData: ''
    })

    wx.setStorage({
      key: 'selectIndex',
      data: -1,
    })
  },

  toggleColor (e) {
    let currId = e.currentTarget.id
    let currSpecId = this.data.skuSpecId
    let skuList = this.data.goodsData.goods_sku
    let sizeList = this.data.goodsData.goods_size_list
    let result = colorSelect(currId, currSpecId, skuList, sizeList)
    
    if (!result.skuImg) {
      result.skuImg = this.data.skuImage
    }

    if (!result.skuPrice) {
      result.skuPrice = this.data.skuPrice
    }

    this.setData({
      goodsData: this.data.goodsData,
      skuColorId: currId,
      colorStyle: currId,
      skuImage: result.skuImg,
      skuPrice: result.skuPrice,
      skuSpecVal: result.skuSpec,
      skuId: result.skuId,
    })
  },

  toggleSpec(e) {
    let currId = e.currentTarget.id
    let currColorId = this.data.skuColorId
    let skuList = this.data.goodsData.goods_sku
    let colorList = this.data.goodsData.goods_color_list
    let result = specSelect(currId, currColorId, skuList, colorList)

    if (!result.skuImg) {
      result.skuImg = this.data.skuImage
    }

    if (!result.skuPrice) {
      result.skuPrice = this.data.skuPrice
    }

    this.setData({
      goodsData: this.data.goodsData,
      skuSpecId: currId,
      specStyle: currId,
      skuImage: result.skuImg,
      skuPrice: result.skuPrice,
      skuSpecVal: result.skuSpec,
      skuId: result.skuId,
    })
  },

  toConfirmPage() {
    if (!this.data.skuColorId) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '请选择商品颜色',
      })
      return false
    }

    if (!this.data.skuSpecId) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '请选择商品规格',
      })
      return false
    }

    if (!this.data.addressData) { // 无收货地址
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '请添加收货地址',
      })
      return false
    }

    let skuFlag = this.data.skuHidden

    if (!this.data.colorStyle || !this.data.specStyle) return false

    this.setData({
      skuHidden: !skuFlag,
      colorStyle: 0,
      specStyle: 0,
    })
    app.request({
      url: requestApi.reservationGoodsInfoUrl,
      method: 'POST',
      data: {
        sku_id: this.data.skuId,
        reservation_id: this.data.goodsData.activity_id,
        address_id: this.data.addressData.id,
      }
    }, (data) => {
      if (data.original.status == 'success') {
        this.doneDialog.showDialog()
      }
    }, error => {
      wx.showToast({
        title: '不可重复预约',
        icon: 'error',
        duration: 1500,
        mask: true
      })
    })
  },

  _confirmKnow() {
    this.doneDialog.hideDialog()
  },
  
  getOrderData(channel) {
    app.request({
      url: requestApi.confirmAddressUrl,
    }, (data) => {
      let addressData

      if (data.original.status == 'success') {
        addressData = data.original.address_list && data.original.address_list.length ? data.original.address_list[0] : ''
        this.setData({
          addressData: addressData,
        })
      }
    }, (error) => {
      wx.showToast({
        title: '失败',
        icon: 'error',
        duration: 1500,
        mask: true
      })
    })
  },

  toAddress: function () {
    this.data.showAddress = false
    let url = '../personal/addressList/addressList?isSelect=select&channel=' + this.data.channel + '&refer=order'

    wx.navigateTo({
      url: url,
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let active_name = this.data.reservationGoodsInfo.activity_name
    
    return {
      title: active_name,
      path: '/pages/reservation/reservation?activity_id=' + this.data.goodsData.activity_id,
    }
  }
})